package com.hkts.naturalgasauthentication.base.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.exceptions.ClientException;
import com.hkts.management.common.utils.BeanConvertUtils;
import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;
import com.hkts.management.common.vo.UserBasicInfoVo;
import com.hkts.naturalgasauthentication.base.dao.mapper.UserMapper;
import com.hkts.naturalgasauthentication.base.entity.*;
import com.hkts.naturalgasauthentication.base.service.*;
import com.hkts.naturalgasauthentication.base.service.mybatis.IUserRoleService;
import com.hkts.naturalgasauthentication.base.vo.UserVo;
import com.hkts.naturalgasauthentication.common.SecurityConstant;
import com.hkts.naturalgasauthentication.common.constant.CommonConstant;
import com.hkts.naturalgasauthentication.common.redis.RedisTemplateHelper;
import com.hkts.naturalgasauthentication.common.vo.SearchVo;
import com.hkts.naturalgasauthentication.config.properties.ManagementTokenProperties;
import com.hkts.naturalgasauthentication.mobile.entity.UserMobiles;
import com.hkts.naturalgasauthentication.mobile.service.UserMobileService;
import com.hkts.naturalgasauthentication.utils.*;
import com.hkts.naturalgasauthentication.utils.sms.SendSms;
import com.qiniu.common.QiniuException;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

//import com.hkts.naturalgasauthentication.mq.FanoutRabbitConfig;
//import org.springframework.amqp.core.AmqpTemplate;
//import org.springframework.amqp.rabbit.core.RabbitTemplate;
@Slf4j
@RestController
@RequestMapping("/authentication")
@Api(value = "用户接口",tags = "用户管理")
public class UserController {
    @Autowired
    private SecurityUtil securityUtil;

    @Autowired
    private QiniuUtil qiniuUtil;


    @Autowired
    private HontUserService userService;


    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private IUserRoleService iUserRoleService;

    @Autowired
    private HontDepartmentService departmentService;

    @Autowired
    private DepartmentHeaderService departmentHeaderService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedisTemplateHelper redisTemplateHelper;

    @Autowired
    private ManagementTokenProperties tokenProperties;

    @Autowired
    private CompanyService companyService;
// @Autowired
//    private AmqpTemplate amqpTemplate;
//    @Autowired
//    RabbitTemplate rabbitTemplate;
    @Autowired
    private UserMobileService userMobileServiceImpl;
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private AliyunSmsUtils aliyunSmsUtils;
    @Autowired
    private SendSms sendSms;
    @PersistenceContext
    private EntityManager entityManager;
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    public Map<String,Object> test(){
        System.out.println("test");
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("statu","ok");
        return map;
    }

    /*
     * 手机验证
     * */
    @GetMapping("/mobileNumber")
    @ApiOperation(value="验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobileNum", value = "货主添加的手机号码", dataType = "string",required = true),
    })
    public Result  mobileNumber(String mobileNum) throws Exception {
        int code = (int) Math.round((Math.random() + 1) * 1000);
        String s = redisTemplate.opsForValue().get(mobileNum);
        if (StringUtils.isNotBlank(s)) {
            return ResultUtil.error("点击过快，请稍后重试！");
        } else {
            Map map = sendSms.sendMessage(mobileNum, String.valueOf(code));
            log.info("短信发送返回数据{}",map.toString());
            List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("resultLists");
            if (!list.get(0).get("resultDesc").equals("success")) {
                return ResultUtil.error(map.get("resultDesc").toString());
            }else{
                redisTemplate.opsForValue().set(mobileNum, String.valueOf(code), 1L, TimeUnit.MINUTES);
            }
        }
        return ResultUtil.data(code);
    }
    //验证短信是否正确
    @GetMapping("/checkCode")
    @ApiOperation(value="校验验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobileNum", value = "货主添加的手机号码", dataType = "string",required = true),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "string",required = true)
    })
    public Result  checkCode(String mobileNum,String code) throws Exception {
        String sessionCode = redisTemplate.opsForValue().get(mobileNum);
        if(StringUtils.isBlank(sessionCode)){
            return  ResultUtil.error("验证码过期!");
        }else if(!sessionCode.equals(code)){
            return  ResultUtil.error("验证码错误!");
        }if(sessionCode.equals(code)){
            return  ResultUtil.success("验证码正确！");
        }

        return ResultUtil.error("未知异常，请联系后端同学！");
    }



    @PostMapping("/saveMobile")
    @ResponseBody
    @ApiOperation(value="添加手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "货主添加的手机号码", dataType = "string",required = true),
            @ApiImplicitParam(name = "code", value = "验证码", dataType = "string",required = true)
    })
    public Result<Object> saveMobile(String mobile, String code){
        // 先获取seesion中的验证码
        String sessionCode = redisTemplate.opsForValue().get(mobile);
        UserMobiles byMobile = userMobileServiceImpl.findByMobile(mobile);
        if (sessionCode == null) {
            return ResultUtil.error("该手机未发验证码！");
        }
        // 判断是否正确
        if (!sessionCode.equals(code)) {
            return ResultUtil.error("验证码错误！");
        }if (byMobile != null){
            return ResultUtil.error("改手机号已添加！");
        }else {
            User currUser = securityUtil.getCurrUser();
            UserMobiles userMobiles = new UserMobiles();
            userMobiles.setUserId(currUser.getId());
            userMobiles.setMobile(mobile);
            userMobileServiceImpl.save(userMobiles);
            return ResultUtil.success("添加成功！");
        }

    }
    @PostMapping("/delMobile")
    @ApiOperation(value="删除手机号")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mobile", value = "需要删除的手机号", dataType = "string",required = true),
    })
    public Result<Object> delMobile(String mobile){
        User currUser = securityUtil.getCurrUser();
        if (mobile.equals(currUser.getMobile())){
            return ResultUtil.error("不能删除当前登录的手机号！");
        }
        UserMobiles byMobile = userMobileServiceImpl.findByMobile(mobile);
        if (byMobile == null){
            return ResultUtil.success("该手机号不存在！");
        }
        userMobileServiceImpl.delete(byMobile.getId());
        return ResultUtil.success("删除成功！");
    }
    @GetMapping("/userInfo")
    @ApiOperation(value = "用户信息")
    public Result userInfo(){
        Long startTime = System.currentTimeMillis();
        User currUser = securityUtil.getCurrUser();
        Long endTime = System.currentTimeMillis();
        Long tempTime = (endTime - startTime);
        System.out.println("获取用户信息时间："+
                (((tempTime/86400000)>0)?((tempTime/86400000)+"d"):"")+
                ((((tempTime/86400000)>0)||((tempTime%86400000/3600000)>0))?((tempTime%86400000/3600000)+"h"):(""))+
                ((((tempTime/3600000)>0)||((tempTime%3600000/60000)>0))?((tempTime%3600000/60000)+"m"):(""))+
                ((((tempTime/60000)>0)||((tempTime%60000/1000)>0))?((tempTime%60000/1000)+"s"):(""))+
                ((tempTime%1000)+"ms"));
       // Company company = companyService.get(currUser.getCompanyId());
        Company company = companyService.getById(currUser.getCompanyId());
        /**
         * 用户信息
         */
        List<UserMobiles> userMobilesByUserId = userMobileServiceImpl.getUserMobilesByUserId(currUser.getId());
        List<String> collect = userMobilesByUserId.stream().map(UserMobiles::getMobile).collect(Collectors.toList());
        collect.add(currUser.getMobile());
        currUser.setContactNumber(collect);
        if(company!=null){
            currUser.setCompanyName(company.getCompanyName());
        }
        return ResultUtil.data(currUser);
    }

    /*
     * 用于远程调用用户信息 公共包vo
     * */
    @GetMapping("/remoteUserBasicInfo")
    public Result<UserBasicInfoVo> remoteUserBasicInfo() {
        User currUser = securityUtil.getCurrUser();
        UserBasicInfoVo vo = new UserBasicInfoVo();
        vo.setId(currUser.getId());
        vo.setAvatar(currUser.getAvatar());
        vo.setNickName(currUser.getNickName());
        vo.setMobile(currUser.getMobile());
        return ResultUtil.data(vo);
    }


    //用于远程调用用户信息
    @ResponseBody
    @GetMapping("/remoteUserInfo")
    public User remoteUserInfo(){
        User currUser = securityUtil.getCurrUser();
        return currUser;
    }

    /**
     * 获取当前登录用户接口
     * @return
     */
    @RequestMapping(value = "/info",method = RequestMethod.GET)
    public Result<User> getUserInfo(){

        User u = securityUtil.getCurrUser();
        /*String avatar = u.getAvatar();
        if(CustomStringUtils.isNotBlank(avatar)&&avatar.contains("uploadFile")){
            String[] uploadFiles = avatar.split("uploadFile");
            u.setAvatar("/uploadFile"+uploadFiles[1]);
        }*/
        List<Permission> permissions = u.getPermissions();
        List<Permission>  perList=new ArrayList<Permission>();
        if (permissions != null){
            for(int i=0;i<permissions.size();i++){
                if(!CustomStringUtils.isNotBlank(permissions.get(i).getParentId())){
                    List<Permission> permissions1 = childrenPerssion(permissions.get(i), permissions);
                    if(permissions1.size()>0){
                        permissions.get(i).setChildren(permissions1);
                    }
                    perList.add(permissions.get(i));
                }
            }
        }
        u.setPermissions(perList);
        // 清除持久上下文环境 避免后面语句导致持久化
        entityManager.clear();
        u.setPassWord(null);
        return new ResultUtil<User>().setData(u);
    }
    public List<Permission> childrenPerssion(Permission permission,List<Permission> list){
        List<Permission> childrenPerssion=new ArrayList<Permission>();
        for(int i=0;i<list.size();i++){
            if(list.get(i).getParentId()!=null&&list.get(i).getParentId().equals(permission.getId())){
                List<Permission> permissions = childrenPerssion(list.get(i), list);
                if(permissions.size()>0){
                    list.get(i).setChildren(permissions);
                }
                childrenPerssion.add(list.get(i));
            }
        }
        return childrenPerssion;
    }
   /** 功能描述:
   *修改货主 手机号和密码
   * @return: 
   * @Author: 杨春科
   * @Date: 2021-07-30 14:14
   * @Description //TODO 
   */
   @RequestMapping(value = "/admin/updateMobileOrPassWord",method = RequestMethod.POST)
   @ApiOperation(value = "管理员修改资料",notes = "需要通过id获取原用户信息 需要username更新缓存")
   @CacheEvict(key = "#u.username")
   public Result<Object> updateMobileOrPassWord(@RequestBody User u){
       User old = userService.get(u.getId());
       //若修改了用户名
       if(!old.getUserName().equals(u.getUserName())){
           //若修改用户名删除原用户名缓存
           redisTemplate.delete("user::"+old.getUserName());
           //判断新用户名是否存在
           if(userService.findByMobileAndId(u.getId(),u.getMobile())){
               return ResultUtil.error("该手机号已注册，请确认后再修改！");
           }
       }

       // 若修改了手机和邮箱判断是否唯一
       if(!old.getMobile().equals(u.getMobile())&&userService.findByMobileAndId(u.getId(),u.getMobile())){
           return ResultUtil.error("该手机号已注册，请确认后再修改！");
       }
       old.setUserName(u.getMobile());
       old.setMobile(u.getMobile());
       if(StringUtils.isNotBlank(u.getPassWord())){
           String encryptPass = new BCryptPasswordEncoder().encode(u.getPassWord());
           old.setPassWord(encryptPass);
       }
       User user=userService.update(old);
       if(user==null){
           return ResultUtil.error("修改失败");
       }
       return ResultUtil.success("修改成功");
   }

    /**
     * 管理员修改资料
     * @param u
     * @param roles
     * @return
     */
    @RequestMapping(value = "/admin/customeEdit",method = RequestMethod.POST)
    @ApiOperation(value = "管理员修改资料",notes = "需要通过id获取原用户信息 需要username更新缓存")
    @CacheEvict(key = "#u.username")
    public Result<Object> customeEdit(User u, @RequestParam(required = false) String[] roles){
        /*User old = userService.get(u.getId());
        u.setMobile(u.getUserName());
        //若修改了用户名
        if(!old.getUserName().equals(u.getUserName())){
            //若修改用户名删除原用户名缓存
            redisTemplate.delete("user::"+old.getUserName());
            //判断新用户名是否存在
            if(userService.findByUsername(u.getUserName())!=null){
                return ResultUtil.error("该用户名已存在");
            }
        }

        // 若修改了手机和邮箱判断是否唯一
        if(!old.getMobile().equals(u.getMobile())&&userService.findByMobile(u.getMobile())!=null){
            return ResultUtil.error("该账号已存在");
        }
*//*        if(!old.getEmail().equals(u.getEmail())&&userService.findByMobile(u.getEmail())!=null){
            return ResultUtil.error("该邮箱已绑定其他账户");
        }*//*
        old.setRoles(u.getRoles());
        old.setNickName(u.getNickName());
        old.setUserName(u.getUserName());
        old.setMobile(u.getMobile());
        old.setDepartmentId(u.getDepartmentId());
        User user=userService.update(old);
        if(user==null){
            return ResultUtil.error("修改失败");
        }*/
        //删除该用户角色
        userRoleService.deleteByUserId(u.getId());
        if(roles.length>0){
            if(roles!=null&&roles.length>0){
                //新角色
                for(String roleId : roles){
                    UserRole ur = new UserRole();
                    ur.setRoleId(roleId);
                    ur.setUserId(u.getId());
                    userRoleService.save(ur);
                }
            }
        }else{
            List<Role> byDefaultRole = roleService.findByDefaultRole(true);
            for(int i=0;i<byDefaultRole.size();i++){
                UserRole ur = new UserRole();
                ur.setRoleId(byDefaultRole.get(i).getId());
                ur.setUserId(u.getId());
                userRoleService.save(ur);
            }
        }

        //手动删除缓存
        /*redisTemplate.delete(CommonConstant.DATA_SYNCHRONIZATION+u.getId());
        redisTemplate.delete("userRole::"+u.getId());
        redisTemplate.delete("userRole::depIds:"+u.getId());
        redisTemplate.delete("userPermission::"+u.getId());
        redisTemplate.delete("permission::userMenuList:"+u.getId());*/
        return ResultUtil.success("修改成功");
    }

    /**
     * 多条件分页获取用户列表
     * @param user
     * @param pageVo
     * @return
     */
    @RequestMapping(value = "/getByCondition",method = RequestMethod.GET)
    @ApiOperation(value = "多条件分页获取用户列表")
    public Result<Page<User>> getByCondition( User user, PageVo pageVo){
        SearchVo searchVo=new SearchVo();
        Page<User> page = userService.findByCondition(user, searchVo, PageUtil.initPage(pageVo));
        for(User u: page.getContent()){
            // 关联公司
            if(StrUtil.isNotBlank(u.getCompanyId())){
                if(companyService.getComPanyBycode(u.getCompanyId())!=null){
                    u.setCompanyName(companyService.getComPanyBycode(u.getCompanyId()).getCompanyName());
                }
            }
            // 关联角色
            List<Role> list = iUserRoleService.findByUserId(u.getId());

            u.setRoles(list);
            // 清除持久上下文环境 避免后面语句导致持久化
            entityManager.clear();
            u.setPassWord(null);
        }
        return new ResultUtil<Page<User>>().setData(page);
    }
    /**
     * 按部门id获取用户列表
     * @param departmentId
     * @return
     */
    @RequestMapping(value = "/getByDepartmentId/{departmentId}",method = RequestMethod.GET)
    @ApiOperation(value = "按部门id获取用户列表")
    public Result<List<User>> getByDepartmentId(@PathVariable String departmentId){
        List<User> list = userService.findByDepartmentId(departmentId);
        entityManager.clear();
        list.forEach(u -> {
            u.setPassWord(null);
        });
        return new ResultUtil<List<User>>().setData(list);
    }

    /**
     * 获取全部用户数据
     * @return
     */
    @RequestMapping(value = "/getAll",method = RequestMethod.GET)
    @ApiOperation(value = "获取全部用户数据")
    public Result<List<User>> getAll(){

        List<User> list = userService.getAll();
        for(User u: list){
            // 关联部门
            if(StrUtil.isNotBlank(u.getDepartmentId())){
                Department department = departmentService.get(u.getDepartmentId());
                if(department!=null){
                    u.setDepartmentTitle(department.getTitle());
                }
            }
            // 清除持久上下文环境 避免后面语句导致持久化
            entityManager.clear();
            u.setPassWord(null);
        }
        return new ResultUtil<List<User>>().setData(list);
    }

    /**
     * 添加用户
     * @param u
     * @param roles
     * @return
     */
    @RequestMapping(value = "/admin/add",method = RequestMethod.POST)
    @ApiOperation(value = "添加用户")
    public Result<Object> regist(@RequestBody User u){
        log.info("用户添加数据{}",u);
        u.setMobile(u.getUserName());
        if(StrUtil.isBlank(u.getUserName()) || StrUtil.isBlank(u.getPassWord())){
            u.setPassWord("123456");
        }
        User currUser = securityUtil.getCurrUser();
        User byUsername = userService.findByUsername(u.getMobile());
        if(byUsername!=null){
            return ResultUtil.error("该用户名已被注册");
        }

        String encryptPass = new BCryptPasswordEncoder().encode(u.getPassWord());
        u.setPassWord(encryptPass);
        u.setUserLevel(2);
        u.setUserName(u.getMobile());
        u.setCreateBy(currUser.getUserName());
        u.setUpdateBy(currUser.getUserName());
        u.setAvatar("picture.hbhkts.cn/426157355382607872");
        User user=userService.save(u);
        if(user==null){
            return ResultUtil.error("添加失败");
        }
  /*      if(roles!=null&&roles.length>0){
            //添加角色
            for(String roleId : roles){
                UserRole ur = new UserRole();
                ur.setUserId(u.getId());
                ur.setRoleId(roleId);
                userRoleService.save(ur);
            }
        }else{
            List<Role> byDefaultRole = roleService.findByDefaultRole(true);
            for(int i=0;i<byDefaultRole.size();i++){
                UserRole ur = new UserRole();
                ur.setUserId(u.getId());
                ur.setRoleId(byDefaultRole.get(i).getId());
                userRoleService.save(ur);
            }
        }*/
       List<Role> byDefaultRole = roleService.findByDefaultRole(true);
        for(int i=0;i<byDefaultRole.size();i++){
            UserRole ur = new UserRole();
            ur.setUserId(u.getId());
            ur.setRoleId(byDefaultRole.get(i).getId());
            userRoleService.save(ur);
        }
        return ResultUtil.data(user);
    }

    /**
     * 后台开启和禁用用户
     * @param userId
     * @param statu
     * @return
     */
    @RequestMapping(value = "/admin/isForbidden",method = RequestMethod.POST)
    @ApiOperation(value = "后台开启和禁用用户")
    public Result<Object> isForbidden( String userId, Integer statu){

        User user = userService.get(userId);

        //redisTemplate.delete(SecurityConstant.USER_TOKEN + user.getUsername());
        redisTemplate.opsForValue().set(SecurityConstant.USER_TOKEN + user.getUserName(),"isForbidden", tokenProperties.getSaveLoginTime(), TimeUnit.DAYS);
        if(user == null){
            ResultUtil.error("通过userId获取用户失败");
        }else if (statu == -1){
            user.setStatus(CommonConstant.USER_STATUS_LOCK);
            userService.update(user);
        }else {
            user.setStatus(CommonConstant.USER_STATUS_NORMAL);
            userService.update(user);
        }
        //手动更新缓存
        redisTemplate.delete("user::"+user.getUserName());
        return ResultUtil.data(null);
    }

    /**
     * 批量通过ids删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "/delByIds/{ids}",method = RequestMethod.DELETE)
    @ApiOperation(value = "批量通过ids删除")
    public Result<Object> delAllByIds(@PathVariable String[] ids){

        for(String id:ids){
            User u = userService.get(id);
            //删除缓存
            redisTemplate.delete("user::" + u.getUserName());
            redisTemplate.delete("userRole::" + u.getId());
            redisTemplate.delete("userRole::depIds:" + u.getId());
            redisTemplate.delete("permission::userMenuList:" + u.getId());
            redisTemplate.delete(CommonConstant.DATA_SYNCHRONIZATION+u.getId());
            Set<String> keys = redisTemplateHelper.keys("department::*");
            redisTemplate.delete(keys);
            userService.delete(id);
            //删除关联角色
            userRoleService.deleteByUserId(id);
            //删除关联部门负责人
            departmentHeaderService.deleteByUserId(id);
        }
        return ResultUtil.success("批量通过id删除数据成功");
    }

    /**
     * 根据部门获取人员
     * @param departmentId
     * @return
     */
    @RequestMapping(value = "/selectUserBuDepartmentId",method = RequestMethod.GET)
    @ApiOperation(value = "根据部门获取人员")
    public Result<Object> selectUserBuDepartmentId(String departmentId){
        List<User>  list=userService.findByDepartmentId(departmentId);
        return ResultUtil.data(list);
    }
    /**
     * 修改密码
     * @param password
     * @param newPass
     * @return
     */
    @RequestMapping(value = "/modifyPass",method = RequestMethod.POST)
    @ApiOperation(value = "修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "oldPassWord", value = "旧密码", dataType = "string",required = true),
            @ApiImplicitParam(name = "newPassWord", value = "新密码", dataType = "string",required = true),
            @ApiImplicitParam(name = "confirmPassword", value = "确认密码", dataType = "string",required = true)
    })

    public Result<Object> modifyPass( @RequestParam String oldPassWord,
                                      @RequestParam String newPassWord,@RequestParam String confirmPassword){
        if(!newPassWord.equals(confirmPassword)){
            return ResultUtil.error("两次新密码不一致！");
        }
        User user = securityUtil.getCurrUser();

        if(!new BCryptPasswordEncoder().matches(oldPassWord, user.getPassWord())){
            return ResultUtil.error("旧密码不正确");
        }

        String newEncryptPass= new BCryptPasswordEncoder().encode(newPassWord);
        user.setPassWord(newEncryptPass);
        userService.update(user);

        //手动更新缓存
        redisTemplate.delete("user::"+user.getUserName());

        return ResultUtil.success("修改密码成功");
    }

    /**
     * 用户头像上传
     * @param file
     * @return
     **/
    @ResponseBody
    @PostMapping("/uploadImage")
    @ApiOperation(value = "用户头像上传")
    public Result<Object> uploadPicture(@ApiParam(name="file",value = "照片",required=true) MultipartFile file) throws QiniuException {
        String oldName = file.getOriginalFilename();
        //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀

        String newName = IDUtils.genImageName();
        assert oldName != null;
        newName = newName + oldName.substring(oldName.lastIndexOf("."));
        //1.3生成文件在服务器端存储的子目录
        String filePath = new DateTime().toString("/yyyyMMdd/");

        //2、把图片上传到图片服务器
        //2.1获取上传的io流
        InputStream input = null;
        try {
            input = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String key =String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
        String iamgePath= qiniuUtil.qiniuInputStreamUpload(input, key);
        /*
         * 保存图片信息
         * */
        User currUser = securityUtil.getCurrUser();
        String avatar = currUser.getAvatar();
        if (avatar != null){
            String substring = avatar.substring(0, avatar.indexOf("/"));
            String path= avatar.substring(substring.length()+1,avatar.length());
            System.out.println(path);
            qiniuUtil.deleteImage(path);
            currUser.setAvatar(iamgePath);
            userService.update(currUser);
            return ResultUtil.data(iamgePath);
        }
        currUser.setAvatar(iamgePath);
        userService.update(currUser);
        return ResultUtil.data(iamgePath);
    }

    /**
     * 用户头像上传
     * @param
     * @param
     * @return
     */
    /*@PostMapping("/updateUserPhoto")
    public Result<Object> upload(MultipartFile uploadFile, HttpServletRequest request){
        String phone = request.getParameter("userName");
        Object o = UploadAndDownloadUtils.uploadPicture(uploadFile);
        String s = "http://192.168.4.3:8081" + o.toString();
        User u = securityUtil.getCurrUser();

  /*  @ResponseBody
    @GetMapping("/showImage")
    public void getWebsiteInformationById(HttpServletRequest request, HttpServletResponse response){
        User currUser = securityUtil.getCurrUser();
        if(currUser!=null){
            byte[] avatar = currUser.getAvatar();
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/png");
            OutputStream outputStream = null;
            try {
                outputStream = response.getOutputStream();
                outputStream.write(avatar);
                outputStream.flush();//排出流中所有数据
            } catch (IOException e) {

                e.printStackTrace();
            }finally {
                try {
                    outputStream.close();//关闭流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }*/
    /*
    * 测试发送消息
    * */
//   @ResponseBody
//    @GetMapping("/sendMessage")
//    public String sendMessage(String msg){
//      // rabbitTemplate.convertAndSend(FanoutRabbitConfig.Reminders_Exchange_Name, FanoutRabbitConfig.Reminders_Queue_Name, msg);
//       Map<String, Object> map = new HashMap<>();
//       map.put("msg", msg);
//       map.put("id", "3333");
//       amqpTemplate.convertAndSend("fanoutExchange", "reminders.queue", map);
//       return "ok";
//    }

    /*
    * 根据用户id 查找用户信息
    * */
    @ResponseBody
    @GetMapping("/getUserBasicInfoVoByuserId/{userId}")
    @ApiOperation("根据userId查询用户基本信息")
    public Result<UserBasicInfoVo> getUserBasicInfoVoByuserId(@ApiParam @PathVariable String userId){
        User user = userService.get(userId);
        UserBasicInfoVo vo = new UserBasicInfoVo();
        vo.setId(user.getId());
        vo.setAvatar(user.getAvatar());
        vo.setNickName(user.getNickName());
        vo.setMobile(user.getMobile());
        return ResultUtil.data(vo);
    }
    /*
     * 根据用户手机号 查找用户信息
     * */
    @ResponseBody
    @GetMapping("/getUserBasicInfoVoByMobile/{phone}")
    @ApiOperation("根据手机号查询用户基本信息")
    public Result<UserBasicInfoVo> getUserBasicInfoVoByMobile(@ApiParam @PathVariable String phone){
        User user = userService.findByMobile(phone);
        UserBasicInfoVo vo = new UserBasicInfoVo();
        vo.setId(user.getId());
        vo.setAvatar(user.getAvatar());
        vo.setNickName(user.getNickName());
        vo.setMobile(user.getMobile());
        return ResultUtil.data(vo);
    }
    /*
     * 根据用户用户昵称 查找用户信息
     * */
    @ResponseBody
    @GetMapping("/getUserByNickName/{nickName}")
    @ApiOperation("根据用户昵称模糊查询查询用户基本信息")
    public Result<List<UserBasicInfoVo>> getUserByNickName(@ApiParam @PathVariable String nickName){
        List<User> users = userService.findByNicknameLike(nickName);
        List<UserBasicInfoVo> userBasicInfoVos=new ArrayList<>();
        for (User item:users){
            UserBasicInfoVo vo = new UserBasicInfoVo();
            vo.setId(item.getId());
            vo.setAvatar(item.getAvatar());
            vo.setNickName(item.getNickName());
            vo.setMobile(item.getMobile());
            userBasicInfoVos.add(vo);
        }
        return ResultUtil.data(userBasicInfoVos);
    }
    /*
     * 根据用户id 查找用户信息
     * */
    @ResponseBody
    @GetMapping("/getUserByuserId/{userId}")
    @ApiOperation("根据userId查询用户及电话列表数据")
    public Result<UserVo> getUserByuserId(@ApiParam @PathVariable String userId){
        User user = userService.get(userId);
        List<UserMobiles> userMobilesByUserId = userMobileServiceImpl.getUserMobilesByUserId(userId);
        UserVo vo= UserVo.getUserVo(user,userMobilesByUserId);
        String userString = JSON.toJSONString(vo);
        redisTemplate.opsForValue().set(CommonConstant.DATA_SYNCHRONIZATION+vo.getUserId(),userString);
//        String s = redisTemplate.opsForValue().get(CommonConstant.DATA_SYNCHRONIZATION + vo.getUserId());
//        UserVo userVo = JSON.parseObject(s, new TypeReference<UserVo>(){});
        return ResultUtil.data(vo);
    }
    /*
     * 根据用户id组 查找用户信息
     * */
    @ResponseBody
    @GetMapping("/getUsersByuserIds")
    @ApiOperation("根据userIds查询用户")
    public Result<Map<String, Object>> getUsersByuserIds(@RequestParam("userIds") List<String> userIds){
        List<User>  users = userService.getUsersByuserIds(userIds);
        if(users==null){
            return ResultUtil.error("用户数据为空");
        }
        Map<String, Object> map=new ConcurrentHashMap<>();
        for (User item:users
             ) {

            UserVo vo= UserVo.getUserVo(item,null);
            map.put(item.getId(),vo);
        }
        return ResultUtil.data(map);
    }

    /*
    * 接受订单远程调用进行微信 端消息推送
    * */

    @ResponseBody
    @GetMapping("/sendMessageByUserId")
    @ApiOperation("根据userId向微信推送催单消息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", dataType = "string",required = true),
            @ApiImplicitParam(name = "msg", value = "消息内容", dataType = "string",required = true),
    })
    public Result sendMessageByUserId(@RequestParam(value = "userId") String userId, @RequestParam(value = "msg") String msg){
        userService.sendMessageByUserId(userId,msg);
        log.info("消息参数userId{}，msg{}",userId,msg);
        return ResultUtil.success("消息发送成功！");
    }
    /*
    * 后台同步货主端数据到redis
    * */
    @ResponseBody
    @GetMapping("/syncDataToRedis")
    @ApiOperation("根据userId查询用户及电话列表数据")
    public Result syncDataToRedis(){
        List<User> all = userService.getAll();
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            all.stream().forEach(user -> {
                List<UserMobiles> userMobilesByUserId = userMobileServiceImpl.getUserMobilesByUserId(user.getId());
                UserVo vo= UserVo.getUserVo(user,userMobilesByUserId);
                String userString = JSON.toJSONString(vo);
                redisTemplate.opsForValue().set(CommonConstant.DATA_SYNCHRONIZATION+vo.getUserId(),userString);
            });
        }, threadPoolExecutor);
        return ResultUtil.success("后台正在同步！");
    }
    /** 功能描述:
    *  修改用户类别
    * @return: 
    * @Author: 杨春科
    * @Date: 2021-08-09 8:53
    * @Description //TODO 
    */
    @ResponseBody
    @PostMapping("/updateUserType")
    @ApiOperation("修改用户类别 货主/管理员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户主键id", dataType = "string", required = true),
            @ApiImplicitParam(name = "type", value = "用户要修改的状态 0是货主，1是管理员", dataType = "int", required = true)
    })
    public Result updateUserType(String id,Integer type){
        User user = userService.get(id);
        user.setType(type);
        userService.update(user);
        return  ResultUtil.success("修改成功！");
    }
   /** 功能描述:
   *根据openid 查询
   * @return:
   * @Author: 杨春科
   * @Date: 2021-08-23 9:40
   * @Description //TODO
   */
   @ResponseBody
   @GetMapping("/getUserByOpenId")
   @ApiOperation("修改用户类别 货主/管理员")
   @ApiImplicitParams({
           @ApiImplicitParam(name = "openId", value = "openId", dataType = "string", required = true)
   })
   public Result<Boolean> getUserByOpenId(String openId){
     boolean isShipper=  userService.getUserByOpenId(openId);
       return  ResultUtil.data(isShipper);
   }
}
